<template>
  <div id="app">
    <div @click="startAllTask">开始生成压缩包</div>
    <div class="print-box" v-for="item in list" :key="item.idSelector" v-show="!false"
      :id="`idSelector${item[0].idSelector}`">
      <Receipt :list="item" />
    </div>
  </div>
</template>

<script>
import Receipt from './components/Receipt.vue';
import html2canvas from 'html2canvas';
import JSZip from 'jszip'
import { saveAs } from 'file-saver';

const zip = new JSZip();

const folder = zip.folder("folder");

const res = new Array(5000).fill(1).map((item, index) => {
  return [
    {
      idSelector: index + 1,
      name: `李小${index + 1}`,
      idCard: '52012119989999',
      date: '2023-07-23 16:32:03',
      time: { code: 'SYSTEM_002', seqNo: 'SHJDGHFSABHJDJKFHJSKADJFASLDF', message: '调用次数已用完' },
      res: '异常情况'
    }
  ]
})

//每次生成多少张图片
const aTaskHasManyImg = 15

const groupNum = res.length / aTaskHasManyImg
const num = Math.floor(groupNum)
const hasManyTask = groupNum > num ? num + 1 : num

let executeTimes = 0
export default {
  components: {
    Receipt
  },
  name: 'App',
  data() {
    return {
      list: []
    }
  },
  methods: {
    async waitingAllTask() {
      if (hasManyTask) {
        await this.createImgSlice(executeTimes)
        executeTimes++
        if (executeTimes < hasManyTask) {
          await this.waitingAllTask()
        }
      }
    },
    async startAllTask() {
      await this.waitingAllTask()
      this.createZip()
    },
    createImgSlice(i = 0) {
      return new Promise((resolve) => {
        const startNum = aTaskHasManyImg * i

        const maxLimitNum = startNum + aTaskHasManyImg
        const endNum = maxLimitNum > res.length ? res.length : maxLimitNum

        const list = []
        for (let index = startNum; index < endNum; index++) {
          list.push(res[index])
        }
        this.list = list

        this.$nextTick(async () => {
          await this.startATask(startNum, endNum)
          resolve(true)
        })
      })
    },
    async startATask(startNum, endNum) {
      const promiseArr = []
      for (let index = startNum; index < endNum; index++) {
        promiseArr.push(this.addFile(`idSelector${index + 1}`, `订单号+Y${index + 1}.jpeg`))
      }
      return Promise.all(promiseArr)
    },
    async addFile(idSelector, fileName) {
      const canvas = await html2canvas(document.querySelector(`#${idSelector}`), {
        quality: 0.9
      });
      await this.addFileSuccess(canvas, fileName)
    },
    addFileSuccess(canvas, fileName) {
      return new Promise((resolve, reject) => {
        canvas.toBlob((blob) => {
          const reader = new FileReader();
          reader.onloadend = () => {
            const imageData64 = reader.result;
            const blobImg = this.base64ToBlob(imageData64);
            folder.file(fileName, blobImg, { base64: true });
            resolve(true)
          };
          reader.readAsDataURL(blob);
        }, 'image/jpeg');
      })
    },
    createZip() {
      zip.generateAsync({ type: "blob" }).then(function (content) {
        saveAs(content, "订单号+Y.zip");
      });
    },
    base64ToBlob(base64) {
      var byteString = atob(base64.split(',')[1]);
      var mimeString = base64.split(',')[0].split(':')[1].split(';')[0];
      var ab = new ArrayBuffer(byteString.length);
      var ia = new Uint8Array(ab);
      for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
      }
      return new Blob([ab], { type: mimeString });
    }
  }
}
</script>

<style>
.print-box {
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  padding: 10px 20px 220px 20px;
}
</style>
